#include "browserwidget.h"
#include "broweserconfiguration.h"
#include "ui_broweserconfiguration.h"
#include "configurationmanager.h"

#include <QMainWindow>
#include <QWebSettings>
#include <QWebPage>

namespace Legenday{

ConfigurationManager::ConfigurationManager(QObject *parent)
	:QObject(parent),
	m_configurationDialog(NULL),
	m_tabWidget(NULL)
{
	setDefaultWebkitConfiguration();
}

ConfigurationManager::~ConfigurationManager()
{
	if (m_configurationDialog != NULL)
		delete m_configurationDialog;
}

void	ConfigurationManager::setTabWidget(QTabWidget *w)
{
	m_tabWidget = w;
}

void	ConfigurationManager::setDefaultWebkitConfiguration()
{
	QWebSettings *settings = QWebSettings::globalSettings();
	settings->setAttribute( QWebSettings::AutoLoadImages, true );
	settings->setAttribute( QWebSettings::JavascriptEnabled, true );
	settings->setAttribute( QWebSettings::JavascriptCanOpenWindows, true );
	settings->setAttribute( QWebSettings::JavascriptCanAccessClipboard, true );
	settings->setAttribute( QWebSettings::LinksIncludedInFocusChain, true );
	settings->setAttribute( QWebSettings::ZoomTextOnly, false );
	settings->setAttribute( QWebSettings::PrintElementBackgrounds, true );
	settings->setAttribute( QWebSettings::LocalStorageEnabled, true );
}

void	ConfigurationManager::showConfigurationDialog()
{
	if (m_configurationDialog == NULL) {
		m_configurationDialog = new BrowserConfigurationDialog;
		connect(m_configurationDialog->ui->buttonBox,SIGNAL(accepted()), this,SLOT(on_configurationDialog_accepted()));
	}

	m_configurationDialog->show();
}

void	ConfigurationManager::hideConfigurationDialog()
{
	if (m_configurationDialog == NULL)
		return;

	m_configurationDialog->hide();
}

BrowserWidget* ConfigurationManager::openNewPage()
{
	if (!m_tabWidget)
		return openNewPopUp();

	BrowserWidget *browser = new BrowserWidget(NULL, this);
	int tabNumber = m_tabWidget->addTab(browser, "Browser" );
	m_tabWidget->setCurrentIndex(tabNumber);
//	connect(browser->,SIGNAL())
	return browser;
}

BrowserWidget* ConfigurationManager::openNewPage(QUrl url)
{
	BrowserWidget *w = openNewPage();
	w->setUrl(url);
	return w;
}

BrowserWidget* ConfigurationManager::openNewPopUp()
{
	BrowserWidget *browser = new BrowserWidget(NULL, this);
	QMainWindow   *window  = new QMainWindow;
	window->setCentralWidget(browser);
	window->show();
	return browser;
}

BrowserWidget* ConfigurationManager::openNewPopUp(QUrl url)
{
	BrowserWidget *w = openNewPopUp();
	w->setUrl(url);
	return w;
}

void ConfigurationManager::on_configurationDialog_accepted()
{
	emit(configurationUpdated());
}

void	ConfigurationManager::on_title_changed()
{

}

}

